"use client";
import { useQueryClient, useQuery } from "@tanstack/react-query";
import * as z from "zod";
import { useEffect, useRef, useState } from "react";
import { CreateTaskSchema } from "@/schemas";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

import { TaskForm, TaskFormRef } from "./form";
import { IPlatform } from "../../types";
export type TaskDialogProps = {
  open: boolean;
  setOpenAction: (value: boolean) => void;
  onSubmitAction: (values: z.infer<typeof CreateTaskSchema>) => void;
};
export function TaskDialog({
  onSubmitAction,
  open,
  setOpenAction,
}: TaskDialogProps) {
  const taskFormRef = useRef<TaskFormRef>(null);

  const [platforms, setPlatforms] = useState<IPlatform[]>([]);
  const platformsQuery = useQuery({
    queryKey: ["platforms"],
    queryFn: () =>
      fetch(`/api/platform/list`, {
        method: "GET",
        //credentials: "include",
        headers: { "Content-Type": "application/json" },
      }).then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          return [];
        }
      }),
  });
  useEffect(() => {
    if (platformsQuery.isPending) return;
    setPlatforms(platformsQuery.data);
  }, [platformsQuery]);

  // const onSubmit = async (values: z.infer<typeof CreateTaskSchema>) => {
  //   try {
  //     const resp = await fetch("/api/task", {
  //       method: "POST",
  //       credentials: "include",
  //       headers: { "Content-Type": "application/json" },
  //       body: JSON.stringify(values),
  //     });

  //     if (!resp.ok) {
  //       const errorData = await resp.json();
  //       toast.error(
  //         `Task creation failed: ${errorData.message || resp.statusText}`,
  //       );
  //       return;
  //     }

  //     toast.info("Task create successful!");
  //     queryClient.invalidateQueries(); // Invalidate only the tasks query
  //     setOpen(false);
  //   } catch (error) {
  //     toast.error(
  //       `Task creation failed: ${error || "An unexpected error occurred."}`,
  //     );
  //   }
  // };

  return (
    <Dialog open={open} onOpenChange={setOpenAction}>
      <DialogTrigger asChild>
        <Button variant="link">新增任务</Button>
      </DialogTrigger>
      <DialogContent className="max-w-fit">
        <DialogHeader className="flex">
          <DialogTitle className="flex justify-center">新增任务</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <TaskForm
          handleSubmit={onSubmitAction}
          ref={taskFormRef}
          platforms={platforms}
        />
        <DialogFooter className="sm:justify-end">
          <Button
            variant={"link"}
            key={"submit"}
            onClick={() => {
              taskFormRef.current?.onSubmit();
            }}
          >
            Submit
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
